<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
  <title>订单管理</title>
  <meta charset="UTF-8">
  <base href="<%=request.getContextPath()%>/">
  <!-- 引入 EasyUI 的默认主题样式 -->
  <link rel="stylesheet" type="text/css" href="static/js/easyui/themes/bootstrap/easyui.css">
  <!-- 引入 EasyUI 的图标样式 -->
  <link rel="stylesheet" type="text/css" href="static/js/easyui/themes/icon.css">
  <!-- 引入自定义的公共CSS -->
  <link rel="stylesheet" type="text/css" href="static/css/common.css"/>
  <!-- 引入 EasyUI 默认的 jQuery -->
  <script src="static/js/easyui/jquery.min.js"></script>
  <!-- 引入 EasyUI 的核心 JS 文件 -->
  <script src="static/js/easyui/jquery.easyui.min.js"></script>
  <!-- 引入 EasyUI 的中文语言包 -->
  <script src="static/js/easyui/locale/easyui-lang-zh_CN.js"></script>
  <!-- 引入自定义的公共脚本 -->
  <script src="static/js/owner/common.js"></script>
  <script src="static/js/owner/axios.min.js"></script>
  <!-- 引入自定义的公共脚本 -->
  <script src="static/js/owner/dataGrid.js"></script>
  <script src="static/js/owner/moment.min.js"></script>
  <!-- 引入doT模板引擎 -->
  <script src="static/js/owner/doT.min.js"></script>
  <!-- daterangepicker 是一个日期范围选择插件 -->
  <link rel="stylesheet" href="static/css/daterangepicker.css">
  <!-- 引入 daterangepicker 的脚本文件 -->
  <script src="static/js/owner/daterangepicker.js"></script>
</head>
<style>
  .searchDiv {
    display: flex;
    flex-direction: row;
    gap: 20px;
    margin: 20px 10px 5px 10px;
    flex-wrap: wrap;
  }
  .operationBtn {
    margin-top: 20px;
    margin-bottom: 10px;
  }
  .item {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  label {
    font-weight: bold;
  }

  .daterange {
    width: 220px !important;
  }

  /* 订单项和发货单样式 */
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    margin-top: 20px;
  }

  .order-total {
    margin-top: 15px;
    text-align: right;
    font-size: 16px;
  }

  .total-amount {
    font-weight: bold;
    color: #F56C6C;
    font-size: 18px;
  }

  .shipment-info {
    margin-bottom: 20px;
  }

  .shipment-details-table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
  }

  .shipment-details-table th,
  .shipment-details-table td {
    border: 1px solid #EBEEF5;
    padding: 10px;
    text-align: center;
  }

  .shipment-details-table th {
    background-color: #F5F7FA;
    color: #606266;
  }

  /* 表单样式 */
  .form-container {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    padding: 10px;
  }

  .form-item {
    flex: 0 0 calc(50% - 15px);
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 15px;
  }

  .form-item label {
    width: 80px;
    margin-right: 10px;
    text-align: right;
    color: #333;
    white-space: nowrap;
  }

  .form-item .input-wrapper {
    flex: 1;
  }

  .form-item-full {
    flex: 0 0 100%;
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    margin-bottom: 15px;
  }

  .form-item-full label {
    width: 80px;
    margin-right: 10px;
    text-align: right;
    color: #333;
    white-space: nowrap;
    padding-top: 8px;
  }

  /* 订单商品表格 */
  .order-items-table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
  }

  .order-items-table th, .order-items-table td {
    border: 1px solid #ddd;
    padding: 8px;
  }

  .order-items-table th {
    background-color: #f2f2f2;
    text-align: left;
  }

  /* 状态标签样式 */
  .status-tag {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
  }
  .status-info { background-color: #e6f7ff; color: #1890ff; }
  .status-warning { background-color: #fff7e6; color: #fa8c16; }
  .status-primary { background-color: #e6f7ff; color: #1890ff; }
  .status-success { background-color: #f6ffed; color: #52c41a; }
</style>
<body>
<div id="toolbar">
  <!-- 查询表单 -->
  <form id="searchForm">
    <div class="searchDiv">
      <div class="item">
        <label>订单编号:</label>
        <input id="orderNo" name="orderNo" class="easyui-textbox">
      </div>
      <div class="item">
        <label>订单状态:</label>
        <select id="status" name="status" class="easyui-combobox" style="width:120px;">
          <option value="">全部</option>
          <option value="0">待确认</option>
          <option value="1">已确认</option>
          <option value="2">已发货</option>
          <option value="3">已完成</option>
        </select>
      </div>
      <div class="item">
        <label>创建时间:</label>
        <input id="dateRange" name="dateRange" class="easyui-textbox daterange">
      </div>

      <div class="searchBtn">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-search" onclick="searchData()">查询</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-reload" onclick="resetSearch()">重置</a>
      </div>
    </div>
  </form>
  <!-- 操作按钮 -->
  <div class="operationBtn">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="addOrder()">新增订单</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-redo" plain="true" onclick="simulateAppOrder()">模拟APP下单</a>
    <a href="shipment/list" class="easyui-linkbutton" iconCls="icon-tip" plain="true">发货管理</a>
  </div>
</div>

<!-- 数据表格 -->
<table id="datagrid" class="easyui-datagrid">
  <thead>
  <tr>
    <th field="ck" checkbox="true"></th>
    <th field="orderNo" width="120">订单编号</th>
    <th field="customerName" width="100">客户名称</th>
    <th field="totalAmount" width="80" formatter="formatCurrency">订单金额</th>
    <th field="status" width="80" formatter="formatStatus">订单状态</th>
    <th field="createTime" width="150">创建时间</th>
    <th field="operation" width="200" formatter="formatOperation">操作</th>
  </tr>
  </thead>
</table>

<!-- 订单表单对话框 -->
<div id="orderDlg" class="easyui-dialog" style="width:800px;height:500px;padding:10px 20px"
     closed="true" buttons="#orderDlg-buttons" modal="true">
  <form id="orderForm" method="post">
    <div class="form-container">
      <div class="form-item">
        <label>客户名称:</label>
        <div class="input-wrapper">
          <input id="customerName" name="customerName" class="easyui-textbox" required="true" style="width:100%">
        </div>
      </div>
      <div class="form-item">
        <label>联系电话:</label>
        <div class="input-wrapper">
          <input id="contactPhone" name="contactPhone" class="easyui-textbox" required="true" style="width:100%">
        </div>
      </div>
      <div class="form-item-full">
        <label>收货地址:</label>
        <div class="input-wrapper">
          <input id="shippingAddress" name="shippingAddress" class="easyui-textbox" required="true" style="width:100%">
        </div>
      </div>
      <div class="form-item-full">
        <label>备注:</label>
        <div class="input-wrapper">
          <input id="remark" name="remark" class="easyui-textbox" multiline="true" style="width:100%;height:60px">
        </div>
      </div>
    </div>

    <!-- 订单商品 -->
    <div class="section-header">
      <h3>订单商品</h3>
      <div>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" onclick="addOrderItem()">添加商品</a>
      </div>
    </div>

    <table id="orderItemsTable" class="order-items-table">
      <thead>
      <tr>
        <th width="40%">商品名称</th>
        <th width="20%">单价</th>
        <th width="15%">数量</th>
        <th width="15%">小计</th>
        <th width="10%">操作</th>
      </tr>
      </thead>
      <tbody id="orderItemsBody">
      <!-- 动态添加行 -->
      </tbody>
    </table>

    <!-- 订单总计 -->
    <div class="order-total">
      <span>订单总计: </span>
      <span class="total-amount" id="orderTotalAmount">¥0.00</span>
    </div>
  </form>
</div>
<div id="orderDlg-buttons">
  <a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="saveOrder()" style="width:90px">保存</a>
  <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#orderDlg').dialog('close')" style="width:90px">取消</a>
</div>

<!-- 发货单对话框 -->
<div id="shipmentDlg" class="easyui-dialog" style="width:1000px;height:550px;padding:10px 20px"
     data-options="closed:true,buttons:'#shipmentDlg-buttons',modal:true,border:'thin',shadow:true">
  <form id="shipmentForm" method="post" novalidate>
    <input type="hidden" id="orderId" name="orderId">
    <div style="margin-bottom:10px">
      <label>订单号:</label>
      <input class="easyui-textbox" id="shipOrderNo" name="orderNo" style="width:200px" disabled>
      <label>客户名称:</label>
      <input class="easyui-textbox" id="shipCustomerName" name="customerName" style="width:200px" disabled>
    </div>
    <div style="margin-bottom:10px">
      <label>收货地址:</label>
      <input class="easyui-textbox" id="shipShippingAddress" name="shippingAddress" style="width:580px" data-options="required:true">
    </div>
    <div style="margin-bottom:10px">
      <label>联系人:</label>
      <input class="easyui-textbox" id="shipContactName" name="contactName" style="width:200px" data-options="required:true">
      <label>联系电话:</label>
      <input class="easyui-textbox" id="shipContactPhone" name="contactPhone" style="width:200px" data-options="required:true">
    </div>
    <div style="margin-bottom:10px">
      <table style="width:100%;height:300px;border:1px solid #ddd;">
        <thead>
          <tr>
            <th style="width:200px;text-align:center;background-color:#f2f2f2;padding:5px;">商品名称</th>
            <th style="width:80px;text-align:center;background-color:#f2f2f2;padding:5px;">订购数量</th>
            <th style="width:80px;text-align:center;background-color:#f2f2f2;padding:5px;">已发货数量</th>
            <th style="width:100px;text-align:center;background-color:#f2f2f2;padding:5px;">可发货数量</th>
            <th style="width:100px;text-align:center;background-color:#f2f2f2;padding:5px;">本次发货数量</th>
            <th style="width:100px;text-align:center;background-color:#f2f2f2;padding:5px;">发货仓库</th>
          </tr>
        </thead>
        <tbody id="shipmentItemsBody">
        </tbody>
      </table>
    </div>
  </form>
</div>
<div id="shipmentDlg-buttons">
  <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveShipment()">保存</a>
  <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="$('#shipmentDlg').dialog('close')">取消</a>
</div>

<!-- 确认发货对话框 -->
<div id="confirmShipmentDlg" class="easyui-dialog" style="width:600px;height:400px;padding:10px 20px"
     closed="true" buttons="#confirmShipmentDlg-buttons" modal="true">
  <div id="confirmShipmentContent">
    <!-- 使用doT模板动态生成内容 -->
  </div>
</div>
<div id="confirmShipmentDlg-buttons">
  <a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="confirmShipment()" style="width:90px">确认发货</a>
  <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#confirmShipmentDlg').dialog('close')" style="width:90px">取消</a>
</div>

<!-- 订单详情对话框 -->
<div id="orderDetailDlg" class="easyui-dialog" style="width:800px;height:500px;padding:10px 20px"
     closed="true" buttons="#orderDetailDlg-buttons" modal="true">
  <div id="orderDetailContent">
    <!-- 使用doT模板动态生成内容 -->
  </div>
</div>
<div id="orderDetailDlg-buttons">
  <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#orderDetailDlg').dialog('close')" style="width:90px">关闭</a>
</div>

<script id="shipmentItemsTmpl" type="text/x-dot-template">
  <div class="shipment-confirm">
    <div class="shipment-info">
      <h4>发货单信息</h4>
      <p><strong>发货单号：</strong>{{=it.shipmentNo}}</p>
      <p><strong>订单编号：</strong>{{=it.orderNo}}</p>
      <p><strong>收货地址：</strong>{{=it.shippingAddress}}</p>
      <p><strong>联系人：</strong>{{=it.contactName}}</p>
      <p><strong>联系电话：</strong>{{=it.contactPhone}}</p>
    </div>

    <div class="shipment-items">
      <h4>发货明细</h4>
      <table class="shipment-details-table">
        <thead>
        <tr>
          <th>商品名称</th>
          <th>发货数量</th>
          <th>仓库</th>
        </tr>
        </thead>
        <tbody>
        {{~it.shipmentItems :item:index}}
        <tr>
          <td>{{=item.productName}}</td>
          <td>{{=item.quantity}}</td>
          <td>{{=item.warehouseName}}</td>
        </tr>
        {{~}}
        </tbody>
      </table>
    </div>
  </div>
</script>

<script id="orderDetailTmpl" type="text/x-dot-template">
  <div class="order-detail">
    <h4>订单基本信息</h4>
    <p><strong>订单编号：</strong>{{=it.orderNo}}</p>
    <p><strong>客户名称：</strong>{{=it.customerName}}</p>
    <p><strong>联系电话：</strong>{{=it.contactPhone}}</p>
    <p><strong>收货地址：</strong>{{=it.shippingAddress}}</p>
    <p><strong>订单状态：</strong>{{=it.statusText}}</p>
    <p><strong>创建时间：</strong>{{=it.createTime}}</p>
    <h4>订单商品</h4>
    <table class="shipment-details-table">
      <thead>
      <tr>
        <th>商品名称</th>
        <th>单价</th>
        <th>订购数量</th>
        <th>已发货数量</th>
        <th>待发货数量</th>
        <th>小计</th>
      </tr>
      </thead>
      <tbody>
      {{~it.orderItems :item:index}}
      <tr>
        <td>{{=item.productName}}</td>
        <td>¥{{=item.productPrice.toFixed(2)}}</td>
        <td>{{=item.quantity}}</td>
        <td>{{=item.shippedQuantity || 0}}</td>
        <td>{{=(item.quantity - (item.shippedQuantity || 0))}}</td>
        <td>¥{{=item.totalPrice.toFixed(2)}}</td>
      </tr>
      {{~}}
      </tbody>
      <tfoot>
      <tr>
        <td colspan="5" style="text-align: right;"><strong>订单总计：</strong></td>
        <td><strong>¥{{=it.totalAmount.toFixed(2)}}</strong></td>
      </tr>
      </tfoot>
    </table>
  </div>
</script>

<script type="text/javascript">
  // 编译doT模板
  var shipmentItemsTmpl = doT.template($('#shipmentItemsTmpl').text());
  var orderDetailTmpl = doT.template($('#orderDetailTmpl').text());

  // 全局变量
  var url;  // 表单提交URL
  var currentOrder;  // 当前操作的订单
  var currentShipment;  // 当前操作的发货单
  var shipmentMap = {};  // 存储订单ID与发货单的映射关系

  $(function() {
    const pageConfig = {
      url: 'order/getData',
      method: 'get',
      emptyMsg: '暂无数据',
    };

    // 调用公共函数初始化 DataGrid
    initializeDataGrid(pageConfig);

    // 初始化日期范围选择器
    initializeDateRangePickers('.daterange');
  });

  // 初始化日期范围选择器
  function initializeDateRangePickers(selector) {
    $(selector).each(function() {
      $(this).textbox({
        icons: [{
          iconCls: 'icon-clear',
          handler: function(e) {
            $(e.data.target).textbox('clear');
          }
        }],
        onChange: function(newValue, oldValue) {
          // 日期变化时的处理逻辑
        }
      });

      // 初始化日期范围选择器
      $(this).textbox('textbox').daterangepicker({
        autoUpdateInput: false,
        locale: {
          cancelLabel: '清除',
          applyLabel: '确定',
          fromLabel: '从',
          toLabel: '到',
          customRangeLabel: '自定义',
          weekLabel: 'W',
          daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
          monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
          firstDay: 1
        }
      });

      $(this).textbox('textbox').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('YYYY-MM-DD') + ' 至 ' + picker.endDate.format('YYYY-MM-DD'));
      });

      $(this).textbox('textbox').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
      });
    });
  }

  // 查询数据
  function searchData() {
    var formData = {};
    var dateRange = $('#dateRange').textbox('getValue');
    var startDate = null;
    var endDate = null;

    if (dateRange) {
      var dates = dateRange.split(' 至 ');
      if (dates.length === 2) {
        startDate = dates[0];
        endDate = dates[1];
      }
    }

    formData = {
      orderNo: $('#orderNo').textbox('getValue'),
      status: $('#status').combobox('getValue'),
      startDate: startDate,
      endDate: endDate
    };

    $('#datagrid').datagrid('load', formData);
  }

  // 重置搜索
  function resetSearch() {
    $('#searchForm').form('clear');
    $('#datagrid').datagrid('load', {});
  }

  // 格式化金额
  function formatCurrency(value, row) {
    if (!value) return '¥0.00';
    return '¥' + parseFloat(value).toFixed(2);
  }

  // 格式化状态
  function formatStatus(value, row) {
    var statusMap = {
      0: { text: '待确认', cls: 'status-info' },
      1: { text: '已确认', cls: 'status-warning' },
      2: { text: '已发货', cls: 'status-primary' },
      3: { text: '已完成', cls: 'status-success' }
    };

    var status = statusMap[value] || { text: '未知', cls: '' };
    return '<span class="status-tag ' + status.cls + '">' + status.text + '</span>';
  }

  // 获取状态文本
  function getStatusText(status) {
    var statusMap = {
      0: '待确认',
      1: '已确认',
      2: '已发货',
      3: '已完成'
    };
    return statusMap[status] || '未知状态';
  }

  // 格式化操作列
  function formatOperation(value, row) {
    var btns = [];
    btns.push('<a href="javascript:void(0)" onclick="viewOrder(' + row.id + ')" class="easyui-linkbutton" iconCls="icon-search" plain="true">查看</a>');

    if (row.status === 0) {
      btns.push('<a href="javascript:void(0)" onclick="confirmOrder(' + row.id + ')" class="easyui-linkbutton" iconCls="icon-ok" plain="true">确认订单</a>');
    }

    if (row.status === 1 || row.status === 2) {
      btns.push('<a href="javascript:void(0)" onclick="createShipment(' + row.id + ')" class="easyui-linkbutton" iconCls="icon-redo" plain="true">新增发货单</a>');
      btns.push('<a href="javascript:void(0)" onclick="viewShipments(' + row.id + ')" class="easyui-linkbutton" iconCls="icon-tip" plain="true">查看发货单</a>');
    }

    if (row.status < 2) {
      btns.push('<a href="javascript:void(0)" onclick="deleteOrder(' + row.id + ')" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>');
    }

    return btns.join('');
  }

  // 在表格加载成功后渲染按钮
  $(function() {
    $('#datagrid').datagrid({
      onLoadSuccess: function() {
        $('.easyui-linkbutton').linkbutton();
      }
    });
  });

  // 新增订单
  function addOrder() {
    $('#orderForm').form('clear');
    $('#orderItemsBody').empty();
    $('#orderTotalAmount').text('¥0.00');
    url = 'order/add';

    // 添加一行默认的订单项
    addOrderItem();

    $('#orderDlg').dialog('open').dialog('setTitle', '新增订单').window('center');
  }

  // 添加订单项
  function addOrderItem() {
    var index = $('#orderItemsBody tr').length;
    var row = $('<tr></tr>');

    // 商品名称
    var nameCell = $('<td></td>');
    var nameInput = $('<input type="text" class="product-name" style="width:90%">');
    nameCell.append(nameInput);

    // 单价
    var priceCell = $('<td></td>');
    var priceInput = $('<input type="text" class="product-price" style="width:80%">');
    priceInput.change(function() {
      calculateItemTotal(index);
    });
    priceCell.append(priceInput);

    // 数量
    var quantityCell = $('<td></td>');
    var quantityInput = $('<input type="number" class="product-quantity" value="1" min="1" style="width:80%">');
    quantityInput.change(function() {
      calculateItemTotal(index);
    });
    quantityCell.append(quantityInput);

    // 小计
    var totalCell = $('<td></td>');
    var totalSpan = $('<span class="item-total">¥0.00</span>');
    totalCell.append(totalSpan);

    // 操作
    var operationCell = $('<td></td>');
    var deleteBtn = $('<a href="javascript:void(0)" class="delete-btn">删除</a>');
    deleteBtn.click(function() {
      $(this).closest('tr').remove();
      calculateOrderTotal();
    });
    operationCell.append(deleteBtn);

    // 组装行
    row.append(nameCell, priceCell, quantityCell, totalCell, operationCell);
    $('#orderItemsBody').append(row);

    // 初始化easyui组件
    nameInput.textbox({
      required: true,
      onChange: function(newValue, oldValue) {
        // 可以添加产品名称变更的业务逻辑
      }
    });

    priceInput.numberbox({
      precision: 2,
      min: 0,
      required: true,
      onChange: function(newValue, oldValue) {
        calculateItemTotal(index);
      }
    });

    quantityInput.numberbox({
      precision: 0,
      min: 1,
      required: true,
      onChange: function(newValue, oldValue) {
        calculateItemTotal(index);
      }
    });

    return row;
  }

  // 计算订单项小计
  function calculateItemTotal(index) {
    var rows = $('#orderItemsBody tr');
    if (index >= rows.length) return;

    var row = $(rows[index]);
    var price = parseFloat(row.find('.product-price').val()) || 0;
    var quantity = parseInt(row.find('.product-quantity').val()) || 0;
    var total = price * quantity;

    row.find('.item-total').text('¥' + total.toFixed(2));
    calculateOrderTotal();
  }

  // 计算订单总价
  function calculateOrderTotal() {
    var total = 0;
    $('#orderItemsBody tr').each(function() {
      var itemTotal = $(this).find('.item-total').text();
      if (itemTotal) {
        total += parseFloat(itemTotal.replace('¥', '')) || 0;
      }
    });

    $('#orderTotalAmount').text('¥' + total.toFixed(2));
    return total;
  }

  // 保存订单
  function saveOrder() {
    // 验证表单
    if (!$('#orderForm').form('validate')) {
      return;
    }

    // 检查订单项
    var items = [];
    var valid = true;

    $('#orderItemsBody tr').each(function(index) {
      var name = $(this).find('.product-name').textbox('getValue');
      var price = parseFloat($(this).find('.product-price').numberbox('getValue'));
      var quantity = parseInt($(this).find('.product-quantity').numberbox('getValue'));

      if (!name || isNaN(price) || isNaN(quantity)) {
        $.messager.alert('错误', '请完整填写订单项信息!', 'error');
        valid = false;
        return false;
      }

      items.push({
        productId: null,
        productName: name,
        productPrice: price,
        quantity: quantity,
        totalPrice: price * quantity
      });
    });

    if (!valid) return;

    if (items.length === 0) {
      $.messager.alert('错误', '请至少添加一个订单项!', 'error');
      return;
    }

    // 构造订单数据
    var formData = {
      customerName: $('#customerName').textbox('getValue'),
      contactPhone: $('#contactPhone').textbox('getValue'),
      shippingAddress: $('#shippingAddress').textbox('getValue'),
      remark: $('#remark').textbox('getValue'),
      orderItems: items
    };

    // 提交订单
    $.ajax({
      url: url,
      type: 'post',
      data: JSON.stringify(formData),
      contentType: 'application/json',
      dataType: 'json',
      success: function(res) {
        if (res.code === 200) {
          $.messager.show({
            title: '成功',
            msg: '订单保存成功!',
            timeout: 2000,
            showType: 'slide'
          });
          $('#orderDlg').dialog('close');
          $('#datagrid').datagrid('reload');
        } else {
          $.messager.alert('错误', res.msg || '订单保存失败!', 'error');
        }
      },
      error: function() {
        $.messager.alert('错误', '网络错误，请稍后重试!', 'error');
      }
    });
  }

  // 查看订单
  function viewOrder(id) {
    $.ajax({
      url: 'order/detail/' + id,
      type: 'get',
      dataType: 'json',
      success: function(res) {
        if (res.code === 200) {
          var order = res.extend.order;
          // 添加状态文本
          order.statusText = getStatusText(order.status);

          // 使用doT模板渲染订单详情
          var html = orderDetailTmpl(order);
          $('#orderDetailContent').html(html);

          $('#orderDetailDlg').dialog('open').dialog('setTitle', '订单详情').window('center');
        } else {
          $.messager.alert('错误', res.msg || '获取订单详情失败!', 'error');
        }
      }
    });
  }

  // 确认订单
  function confirmOrder(id) {
    $.messager.confirm('确认', '确定要确认此订单吗?', function(r) {
      if (r) {
        $.ajax({
          url: 'order/confirm/' + id,
          type: 'put',
          dataType: 'json',
          success: function(res) {
            if (res.code === 200) {
              $.messager.show({
                title: '成功',
                msg: '订单已确认!',
                timeout: 2000,
                showType: 'slide'
              });
              $('#datagrid').datagrid('reload');
            } else {
              $.messager.alert('错误', res.msg || '确认订单失败!', 'error');
            }
          }
        });
      }
    });
  }

  // 删除订单
  function deleteOrder(id) {
    $.messager.confirm('确认', '确定要删除此订单吗?', function(r) {
      if (r) {
        $.ajax({
          url: 'order/delete/' + id,
          type: 'delete',
          dataType: 'json',
          success: function(res) {
            if (res.code === 200) {
              $.messager.show({
                title: '成功',
                msg: '订单已删除!',
                timeout: 2000,
                showType: 'slide'
              });
              $('#datagrid').datagrid('reload');
            } else {
              $.messager.alert('错误', res.msg || '删除订单失败!', 'error');
            }
          }
        });
      }
    });
  }

  // 生成发货单
  function createShipment(orderId) {
    // 先清空表单
    $('#shipmentForm').form('clear');
    $('#shipmentItemsBody').empty();

    // 获取订单详情
    $.ajax({
      url: 'order/detail/' + orderId,
      type: 'get',
      dataType: 'json',
      success: function(res) {
        if (res.code === 200) {
          var order = res.extend.order;
          currentOrder = order;

          // 设置发货单表单的基本信息
          $('#orderId').val(order.id);
          $('#shipOrderNo').textbox('setValue', order.orderNo);
          $('#shipCustomerName').textbox('setValue', order.customerName);
          $('#shipShippingAddress').textbox('setValue', order.shippingAddress);
          $('#shipContactName').textbox('setValue', order.customerName);
          $('#shipContactPhone').textbox('setValue', order.contactPhone);

          // 获取可发货数量（订单总数量减去已发货数量）
          $.ajax({
            url: 'shipment/getShippedItems/' + orderId,
            type: 'get',
            dataType: 'json',
            success: function(shippedRes) {
              var shippedItems = shippedRes.code === 200 ? shippedRes.extend.shippedItems : {};

              // 动态添加发货商品列表
              if (order.orderItems && order.orderItems.length > 0) {
                order.orderItems.forEach(function(item, index) {
                  var shippedQuantity = item.shippedQuantity || 0;
                  var remainingQuantity = item.quantity - shippedQuantity;

                  if (remainingQuantity <= 0) {
                    return; // 跳过已全部发货的商品
                  }

                  var row = $('<tr></tr>');

                  // 商品名称
                  var nameCell = $('<td></td>').text(item.productName);

                  // 订购总数量
                  var orderQuantityCell = $('<td align="center"></td>').text(item.quantity);

                  // 已发货数量
                  var shippedQuantityCell = $('<td align="center"></td>').text(shippedQuantity);

                  // 剩余可发货数量
                  var remainingQuantityCell = $('<td align="center"></td>').text(remainingQuantity);

                  // 本次发货数量
                  var quantityCell = $('<td></td>');
                  var quantityInput = $('<input type="text" class="ship-quantity" data-item-id="' + item.id + '">');
                  quantityCell.append(quantityInput);

                  // 仓库
                  var warehouseCell = $('<td></td>');
                  var warehouseSelect = $('<select class="warehouse-select" data-item-id="' + item.id + '"></select>');
                  warehouseCell.append(warehouseSelect);

                  // 组装行
                  row.append(nameCell, orderQuantityCell, shippedQuantityCell, remainingQuantityCell, quantityCell, warehouseCell);
                  $('#shipmentItemsBody').append(row);

                  // 初始化easyui组件
                  quantityInput.numberbox({
                    value: 1, // 默认发货1个
                    min: 1,
                    max: remainingQuantity,
                    required: true
                  });

                  warehouseSelect.combobox({
                    data: [
                      {value: '1', text: '主仓库'},
                      {value: '2', text: '南京仓库'},
                      {value: '3', text: '上海仓库'}
                    ],
                    valueField: 'value',
                    textField: 'text',
                    panelHeight: 'auto',
                    editable: false,
                    required: true,
                    value: '1'
                  });
                });
              }

              $('#shipmentDlg').dialog('open').dialog('setTitle', '创建发货单').window('center');
            }
          });
        } else {
          $.messager.alert('错误', res.msg || '获取订单详情失败!', 'error');
        }
      }
    });
  }

  // 保存发货单
  function saveShipment() {
    if (!$('#shipmentForm').form('validate')) {
      return;
    }

    // 构造发货单商品列表
    var items = [];
    var valid = true;

    $('#shipmentItemsBody tr').each(function() {
      var itemId = $(this).find('.ship-quantity').data('item-id');
      var quantity = parseInt($(this).find('.ship-quantity').numberbox('getValue'));
      var warehouseId = $(this).find('.warehouse-select').combobox('getValue');
      var warehouseName = $(this).find('.warehouse-select').combobox('getText');

      if (!itemId || !quantity || !warehouseId) {
        valid = false;
        return false;
      }

      // 查找对应的订单项
      var orderItem = null;
      for (var i = 0; i < currentOrder.orderItems.length; i++) {
        if (currentOrder.orderItems[i].id == itemId) {
          orderItem = currentOrder.orderItems[i];
          break;
        }
      }

      if (orderItem) {
        items.push({
          orderItemId: itemId,
          productId: orderItem.productId,
          productName: orderItem.productName,
          quantity: quantity,
          warehouseId: warehouseId,
          warehouseName: warehouseName
        });
      }
    });

    if (!valid) {
      $.messager.alert('错误', '请完整填写发货信息!', 'error');
      return;
    }

    if (items.length === 0) {
      $.messager.alert('错误', '没有可发货的商品!', 'error');
      return;
    }

    // 构造发货单数据
    var shipmentData = {
      orderId: currentOrder.id,
      shippingAddress: $('#shipShippingAddress').textbox('getValue'),
      contactName: $('#shipContactName').textbox('getValue'),
      contactPhone: $('#shipContactPhone').textbox('getValue'),
      shipmentItems: items
    };

    // 保存发货单
    $.ajax({
      url: 'shipment/createFromOrder/' + currentOrder.id,
      type: 'post',
      data: JSON.stringify(shipmentData),
      contentType: 'application/json',
      dataType: 'json',
      success: function(res) {
        if (res.code === 200) {
          $.messager.show({
            title: '成功',
            msg: '发货单创建成功!',
            timeout: 2000,
            showType: 'slide'
          });

          // 保存发货单与订单的映射关系，用于前端检查
          var shipment = {
            id: res.extend.id,
            shipmentNo: res.extend.shipmentNo,
            orderId: currentOrder.id,
            orderNo: currentOrder.orderNo,
            status: 0, // 待发货
            shippingAddress: shipmentData.shippingAddress,
            contactName: shipmentData.contactName,
            contactPhone: shipmentData.contactPhone,
            shipmentItems: items
          };

          shipmentMap[currentOrder.id] = shipment;

          $('#shipmentDlg').dialog('close');
          $('#datagrid').datagrid('reload');
        } else {
          $.messager.alert('错误', res.msg || '发货单创建失败!', 'error');
        }
      }
    });
  }

  // 打开确认发货对话框
  function openConfirmShipment(orderId) {
    $.ajax({
      url: 'order/detail/' + orderId,
      type: 'get',
      dataType: 'json',
      success: function(res) {
        if (res.code === 200) {
          currentOrder = res.extend.order;

          // 获取发货单信息
          var shipment = shipmentMap[orderId];

          // 如果没有本地缓存，尝试从服务器获取
          if (!shipment) {
            $.ajax({
              url: 'shipment/getByOrderId/' + orderId,
              type: 'get',
              async: false,
              dataType: 'json',
              success: function(result) {
                if (result.code === 200) {
                  shipment = result.extend.shipment;
                  shipmentMap[orderId] = shipment;
                }
              }
            });
          }

          if (!shipment) {
            $.messager.alert('错误', '找不到对应的发货单!', 'error');
            return;
          }

          currentShipment = shipment;

          // 使用doT模板渲染确认发货界面
          var html = shipmentItemsTmpl(shipment);
          $('#confirmShipmentContent').html(html);

          $('#confirmShipmentDlg').dialog('open').dialog('setTitle', '确认发货').window('center');
        } else {
          $.messager.alert('错误', res.msg || '获取订单详情失败!', 'error');
        }
      }
    });
  }

  // 确认发货
  function confirmShipment() {
    if (!currentShipment || !currentShipment.id) {
      $.messager.alert('错误', '发货单信息不完整!', 'error');
      return;
    }

    $.ajax({
      url: 'shipment/confirm/' + currentShipment.id,
      type: 'put',
      dataType: 'json',
      success: function(res) {
        if (res.code === 200) {
          $.messager.show({
            title: '成功',
            msg: '发货成功!',
            timeout: 2000,
            showType: 'slide'
          });

          // 更新本地状态
          if (currentOrder) {
            currentOrder.status = 2; // 已发货
          }
          if (currentShipment) {
            currentShipment.status = 1; // 已发货
          }

          $('#confirmShipmentDlg').dialog('close');
          $('#datagrid').datagrid('reload');
        } else {
          $.messager.alert('错误', res.msg || '确认发货失败!', 'error');
        }
      }
    });
  }

  // 模拟APP下单
  function simulateAppOrder() {
    $.messager.confirm('确认', '确定要模拟APP下单吗?', function(r) {
      if (r) {
        $.ajax({
          url: 'order/appOrder',
          type: 'post',
          dataType: 'json',
          success: function(res) {
            if (res.code === 200) {
              $.messager.show({
                title: '成功',
                msg: 'APP下单成功，订单号: ' + res.extend.orderNo,
                timeout: 3000,
                showType: 'slide'
              });
              $('#datagrid').datagrid('reload');
            } else {
              $.messager.alert('错误', res.msg || '模拟下单失败!', 'error');
            }
          }
        });
      }
    });
  }

  // 判断订单是否有发货单
  function hasShipment(orderId) {
    // 本地判断
    if (shipmentMap[orderId] !== undefined) {
      return true;
    }

    // 也可以调用后端接口进行实时检查
    var hasShip = false;
    $.ajax({
      url: 'shipment/exists/' + orderId,
      type: 'get',
      async: false, // 同步请求，等待结果
      dataType: 'json',
      success: function(res) {
        if (res.code === 200 && res.extend.exists) {
          hasShip = true;
        }
      }
    });

    return hasShip;
  }

  // 获取仓库名称
  function getWarehouseName(warehouseId) {
    var warehouseMap = {
      1: '主仓库',
      2: '南京仓库',
      3: '上海仓库'
    };
    return warehouseMap[warehouseId] || '未知仓库';
  }

  // 查看订单关联的发货单列表
  function viewShipments(orderId) {
    // 打开发货单管理页面，并按订单号筛选
    var url = 'shipment/list?orderNo=' + orderId;
    window.open(url, '_blank');
  }
</script>
</body>
</html>
